{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "import jieba\n",
    "import Spider\n",
    "\n",
    "def score(item, query):\n",
    "    score = 0\n",
    "    # TODO 对query查询的分词避免重复\n",
    "    for keyword in jieba.cut(query.lower()):\n",
    "        title_score = item[1].lower().count(keyword.lower())\n",
    "        content_score = item[2].lower().count(keyword.lower())\n",
    "        score += title_score * 5 + content_score * 3\n",
    "    return score\n",
    "\n",
    "\n",
    "class MySearcherC9V0:\n",
    "    \"\"\"\n",
    "    第七次课升级的搜索类版本：\n",
    "    1、__init__()初始化过程加载自定义分词词典\n",
    "    2、build_cache()改用jieba.cut_for_search进行分词\n",
    "    3、search()对查询分词\n",
    "    4、search()对分词结果取posting\n",
    "    5、search()对posting lists进行合并(交集)\n",
    "    6、build_cache()将posting保存格式改成只用doc_id(方便集合运算)\n",
    "    7、rank()实现对候选文档打分排序\n",
    "    8、score()实现对查询中包含的多词统计词频计分\n",
    "    \"\"\"\n",
    "    def __init__(self, scale: int=1):\n",
    "        self.docs = list()\n",
    "        self.load_data()\n",
    "        if scale > 1:\n",
    "            self.docs *= scale  # 文档规模倍增，用于测试搜索速度\n",
    "        self.cache = dict()\n",
    "        self.vocab = set()\n",
    "        self.lower_preprocess()\n",
    "        jieba.load_userdict('./dict.txt')\n",
    "        self.build_cache()\n",
    "\n",
    "    def load_data(self, data_file_name='./news_list.pkl'):\n",
    "        if os.path.exists(data_file_name):\n",
    "            self.docs = Spider.pickle_load(data_file_name)\n",
    "        else:\n",
    "            Spider.pickle_save(data_file_name)\n",
    "            self.docs = Spider.pickle_load(data_file_name)\n",
    "\n",
    "    def search(self, query):\n",
    "        result = None\n",
    "        for keyword in jieba.cut(query.lower()):\n",
    "            if keyword in self.cache:\n",
    "                if result is None:\n",
    "                    result = self.cache[keyword]\n",
    "                else:\n",
    "                    result = result & self.cache[keyword]\n",
    "            else:\n",
    "                result = set()\n",
    "                break\n",
    "        if result is None:\n",
    "            result = set()\n",
    "        sorted_result = self.rank(query, result)\n",
    "        return sorted_result\n",
    "\n",
    "    def rank(self, query, result_set):\n",
    "        result = list()\n",
    "        for doc_id in result_set:\n",
    "            result.append([doc_id, score(self.docs[doc_id], query)])\n",
    "\n",
    "        result.sort(key=lambda x: x[1], reverse=True)\n",
    "        return result\n",
    "\n",
    "    # def render_search_result(self, keyword):\n",
    "    #     count = 0\n",
    "    #     for item in self.search(keyword):\n",
    "    #         count += 1\n",
    "    #         print(f'{count}[{item[1]}] {highlight(self.docs[item[0]][1], keyword)}')\n",
    "\n",
    "    def build_cache(self):\n",
    "        \"\"\"用分词（用文档过滤词库）的方式初始化缓存（构建索引）\"\"\"\n",
    "        doc_id = 0\n",
    "        for doc in self.docs:\n",
    "            doc_word_set = set()\n",
    "            for word in jieba.cut_for_search(doc[3]):\n",
    "                if word not in doc_word_set:\n",
    "                    result_item = doc_id\n",
    "                    if word not in self.cache:\n",
    "                        self.cache[word] = {result_item}\n",
    "                    else:\n",
    "                        self.cache[word].add(result_item)\n",
    "                    self.vocab.add(word)\n",
    "                    doc_word_set.add(word)\n",
    "            doc_id += 1\n",
    "\n",
    "    def lower_preprocess(self):\n",
    "        for doc_id in range(len(self.docs)):\n",
    "            self.docs[doc_id].append(\n",
    "                (self.docs[doc_id][1] + ' ' + self.docs[doc_id][2]).lower())\n",
    "\n",
    "    def simple_test(self):\n",
    "        assert(len(self.search('tiktok')) > 1)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "collapsed": false,
    "jupyter": {
     "outputs_hidden": false
    },
    "pycharm": {
     "name": "#%%\n"
    }
   },
   "outputs": [],
   "source": [
    "def highlight(item, query: str, side_len: int = 12) -> str:\n",
    "    positions = list()\n",
    "    query_words = list(jieba.cut(query))  # 把生成器强制转换为列表\n",
    "    i = 0\n",
    "    content_lower = item[2].lower()\n",
    "    word_start_map = list()\n",
    "    word_end_map = list()\n",
    "    last_word_end = -1\n",
    "    len_content_lower = len(content_lower)\n",
    "    segments = list()\n",
    "    for keyword in query_words:\n",
    "        idx = content_lower.find(keyword.lower())\n",
    "        positions.append(idx)\n",
    "    for keyword in jieba.cut(content_lower):\n",
    "        # 用于实现提取摘要时“整词切分”，避免出现截取摘要时首尾的词被截断\n",
    "        current_word_start = last_word_end + 1\n",
    "        current_word_end = current_word_start + len(keyword) - 1\n",
    "        for _ in range(current_word_start, current_word_end+1):\n",
    "            word_start_map.append(current_word_start)\n",
    "            word_end_map.append(current_word_end)\n",
    "        last_word_end = current_word_end\n",
    "    positions.sort()\n",
    "    while i < len(positions):\n",
    "        start_pos = max(positions[i] - side_len, 0)\n",
    "        end_pos = min(positions[i] + side_len, len_content_lower-1)\n",
    "        # 用于实现合并相邻且有部分重合的摘要\n",
    "        while (i < len(positions) - 1) and (positions[i+1] - positions[i] < side_len*2):\n",
    "            end_pos = min(positions[i+1] + side_len, len_content_lower-1)\n",
    "            i += 1\n",
    "        start_ellipsis = '...' if start_pos > 0 else ''\n",
    "        end_ellipsis = '...' if end_pos < len_content_lower else ''\n",
    "        segments.append(start_ellipsis + item[2][word_start_map[start_pos]: word_end_map[end_pos]] + end_ellipsis)\n",
    "        i += 1\n",
    "    result = text = item[1] + '<br/>' + ''.join(segments)\n",
    "    text_lower = text.lower()\n",
    "    for keyword in query_words:\n",
    "        # 高亮部分\n",
    "        idx = text_lower.find(keyword.lower())\n",
    "        if idx >= 0:\n",
    "            ori_word = text[idx:idx+(len(keyword))]\n",
    "            result = result.replace(ori_word, f'<span style=\"color:red\";>{ori_word}</span>')\n",
    "    return result"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {
    "collapsed": false,
    "jupyter": {
     "outputs_hidden": false
    },
    "pycharm": {
     "name": "#%%\n"
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": "'<span style=\"color:red\";>华为</span>Mate40来了 硬刚iPhone12！买哪个？网友吵起来了<br/><span style=\"color:red\";>华为</span>Mate40来了，硬......10月，<span style=\"color:red\";>华为</span>Mate 40<span style=\"color:red\";>系列</span><span style=\"color:red\";>手机</span>将与iPhone 12<span style=\"color:red\";>系列</span><span style=\"color:red\";>手机</span>正面对...'"
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "highlight([\n",
    "    '',\n",
    "    '华为Mate40来了 硬刚iPhone12！买哪个？网友吵起来了',\n",
    "    '华为Mate40来了，硬刚iPhone12！该买哪一个？网友吵起来了） 每经编辑 何小桃这个10月，华为Mate 40系列手机将与iPhone 12系列手机正面对决'\n",
    "], '对决华为系列手机')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "collapsed": false,
    "jupyter": {
     "outputs_hidden": false
    },
    "pycharm": {
     "name": "#%%\n"
    }
   },
   "outputs": [],
   "source": [
    "class MySearcherC9V1(MySearcherC9V0):\n",
    "    def render_search_result(self, query):\n",
    "        count = 0\n",
    "        result = ''\n",
    "        for item in self.search(query):\n",
    "            count += 1\n",
    "            result += f'{count}[{item[1]}] {highlight(self.docs[item[0]], query)}\\n'\n",
    "        return result"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {
    "collapsed": false,
    "jupyter": {
     "outputs_hidden": false
    },
    "pycharm": {
     "name": "#%%\n"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Wall time: 1.54 s\n"
     ]
    }
   ],
   "source": [
    "%%time\n",
    "searcher_v1 = MySearcherC9V1()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {
    "collapsed": false,
    "jupyter": {
     "outputs_hidden": false
    },
    "pycharm": {
     "name": "#%%\n"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1[235] 传<span style=\"color:red\";>华为</span>预计今年智能<span style=\"color:red\";>手机</span>出货量同比减少60%，降至7000万部<br/>...，据供应链消息人士透露，<span style=\"color:red\";>华为</span>已通知其供应商，预计......7000万至8000万部智能<span style=\"color:red\";>手机</span>的零部件。而且<span style=\"color:red\";>华为</span>的零部...\n",
      "2[131] <span style=\"color:red\";>华为</span>将在英国起诉汇丰，要拿到孟晚舟案关键文件<br/>...消息，当地时间12日，中国<span style=\"color:red\";>华为</span>公司首席财务官孟晚舟......发生了很多事，有关于<span style=\"color:red\";>华为</span><span style=\"color:red\";>手机</span>出货量的报道，也有关...\n",
      "3[116] <span style=\"color:red\";>华为</span>推\"智慧养猪\"，任正非曾称如果养猪可能也是状元<br/>...生猪养殖业真香，连电信巨头<span style=\"color:red\";>华为</span>都想进去分一杯羹了。近......突破，任正非表示，<span style=\"color:red\";>华为</span>不靠<span style=\"color:red\";>手机</span>业务也可以存活。此前任正...\n",
      "4[102] <span style=\"color:red\";>华为</span>推“智慧养猪”，任正非：<span style=\"color:red\";>华为</span>不靠<span style=\"color:red\";>手机</span>也能活<br/>...近日，任正非首次公开提及<span style=\"color:red\";>华为</span>“南泥湾”计划，即生产自......突破，任正非表示，<span style=\"color:red\";>华为</span>不靠<span style=\"color:red\";>手机</span>业务也可以存活。随后...\n",
      "5[99] <span style=\"color:red\";>华为</span>折叠屏<span style=\"color:red\";>手机</span><span style=\"color:red\";>华为</span>MateX2将于下周一20时发布<br/>财联社2月18日讯，据<span style=\"color:red\";>华为</span>官微，<span style=\"color:red\";>华为</span>折叠屏<span style=\"color:red\";>手机</span>2将于2月22日20...\n",
      "6[98] <span style=\"color:red\";>华为</span>Mate X2镜头供应商为舜宇光学和欧菲光 屏幕为三星<br/>《科创板日报》3日讯，<span style=\"color:red\";>华为</span>即将在2月22号发布......，有消息称<span style=\"color:red\";>华为</span>将会出售其<span style=\"color:red\";>手机</span>业务包括Mate/P系...\n",
      "7[93] <span style=\"color:red\";>华为</span>供应链公司：已向<span style=\"color:red\";>华为</span>P50<span style=\"color:red\";>手机</span>供货，供货时间有延后<br/>据<span style=\"color:red\";>华为</span><span style=\"color:red\";>手机</span>供应链公司，该公司已逐...\n",
      "8[90] 小米正式发布隔空充电技术 雷军称可实现单设备5瓦远距离充电<br/>...内置5个相位干涉天线，可对<span style=\"color:red\";>手机</span>进行毫秒级空间定位，精......变化，苹果排名飙升至第一，<span style=\"color:red\";>华为</span>已被小米、和vivo反...\n",
      "9[77] 除了欢迎拜登致电<span style=\"color:red\";>华为</span>，任正非还谈了孟晚舟、退休时间、5G转让等<br/>...任正非接受中外媒体采访，就<span style=\"color:red\";>华为</span>发展、产业、个人生活......发生了很多事，有关于<span style=\"color:red\";>华为</span><span style=\"color:red\";>手机</span>出货量的报道，也有关...\n",
      "10[68] 外媒：夺回<span style=\"color:red\";>华为</span>失去的市场，荣耀仍能重现辉煌<br/>荣耀已与<span style=\"color:red\";>华为</span>分道扬镳，并于上个月发......第一款智能V40。虽然这款<span style=\"color:red\";>手机</span>目前只在中国销售，但荣...\n",
      "11[68] 争国内第一！荣耀想打败<span style=\"color:red\";>华为</span>小米，靠3599的V40行么？<br/>...月前，荣耀正式宣布独立。<span style=\"color:red\";>华为</span>官方称这是“产业链的一......问题。更重要的是，其他国产<span style=\"color:red\";>手机</span>品牌已经虎视眈眈，瞄...\n",
      "12[48] 小米国内机型不再支持自行安装GMS框架，国际版不受影响<br/>...注意到一些报道中提及小米<span style=\"color:red\";>手机</span>不支持GMS服务，事......年5月16日后，美国制裁<span style=\"color:red\";>华为</span>，谷歌的GMS不再为华...\n",
      "13[21] 男子年会中奖“清空购物车”，不料里面有套房，老板：过分了<br/>...从大到小，价值也是不等，有<span style=\"color:red\";>手机</span>、代金券等等，有的实......9-9-6” 中二选一。<span style=\"color:red\";>华为</span>：暖心了，离职后还能收...\n",
      "\n"
     ]
    }
   ],
   "source": [
    "print(searcher_v1.render_search_result('华为手机'))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.8"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}